package com.example.srm.auth.intercept;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.example.srm.auth.service.SysUserTokenService;
import com.example.srm.common.exception.MyException;
import com.example.srm.constant.PermissionConstant;
import com.example.srm.constant.SysUserTokenConstant;
import com.example.srm.domain.SysUserToken;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author pfk
 * @creatTime 2022/01/20 14:33
 * @describe 拦截器：主要用于拦截未登录用户
 */
@Component
@Slf4j
public class MyInterceptor implements HandlerInterceptor {

    @Autowired
    private SysUserTokenService tokenService;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
      if (handler instanceof HandlerMethod){
          String uri = request.getRequestURI();
          if (uri.contains("/login")||uri.contains("/error")){
              return true;
          }

          log.info("处理接口【"+uri+"】前");
          log.info("正在获取token...");
          String token = request.getHeader(PermissionConstant.AUTH_TOKEN);
          if (token == null) {
              log.info("未获取到token");
              throw new MyException("未获取到token,请登录",401);
          }else {
              log.info("token："+token);
              //检验token是否过期
              SysUserToken userToken = tokenService.getOne(new QueryWrapper<SysUserToken>().eq(SysUserTokenConstant.TOKEN, token));
              if(userToken == null || userToken.getExpireTime().getTime() < System.currentTimeMillis()){
                  throw  new MyException("token已过期，请登录",401);
              }else {
                  return true;
              }
          }

      }else {
          return true;
      }
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
//        HandlerInterceptor.super.postHandle(request, response, handler, modelAndView);
//        String uri = request.getRequestURI();
//        log.info("处理接口【"+uri+"】后");
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
//        HandlerInterceptor.super.afterCompletion(request, response, handler, ex);
//        String uri = request.getRequestURI();
//        log.info("接口【"+uri+"】返回视图后，清理结果资源，必须要在处理请求前的方法返回值为true");
    }
}
